package com.incar.util;

import android.content.Context;
import android.util.Log;

import com.incar.aiuidemo.AIUIApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

public class FileUtil {
    /**
     * 把assets目录下的文件夹复制到指定路径
     */
    public static void copyAssetFolder(String assetFolder, String targetPath) {
        try {
            Context context = AIUIApplication.getContext();
            File targetDir = new File(targetPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            // 输出assets目录下的文件列表，用于调试
            String[] files = context.getAssets().list(assetFolder);
            Log.d("FileUtil", "assets/" + assetFolder + " 目录下的文件列表: " + Arrays.toString(files));

            for (String file : files) {
                String sourcePath = assetFolder + "/" + file;
                String targetFilePath = targetPath + "/" + file;

                // 输出当前处理的文件路径
                Log.d("FileUtil", "正在处理: " + sourcePath + " --> " + targetFilePath);

                // 检查文件是否为目录
                if (isAssetDirectory(context, sourcePath)) {
                    copyAssetFolder(sourcePath, targetFilePath);
                } else {
                    copyAssetFile(sourcePath, targetFilePath, context);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("FileUtil", "复制资源文件失败: " + e.getMessage());
        }
    }

    /**
     * 判断assets中的路径是否为目录
     */
    private static boolean isAssetDirectory(Context context, String assetPath) {
        try {
            // 如果是文件，list()方法会抛出异常
            String[] list = context.getAssets().list(assetPath);
            return list != null && list.length > 0;
        } catch (IOException e) {
            // 说明是文件而非目录
            return false;
        }
    }

    /**
     * 复制单个文件
     */
    private static void copyAssetFile(String assetPath, String targetPath, Context context) throws IOException {
        Log.d("FileUtil", "开始复制文件: " + assetPath + " --> " + targetPath);

        try (InputStream is = context.getAssets().open(assetPath);
             OutputStream os = new FileOutputStream(targetPath)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            Log.e("FileUtil", "文件未找到: " + assetPath + "，请检查assets目录结构");
            throw e;
        }
    }
}